package com.da.lon.wang.xlg.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.appkefu.lib.interfaces.KFAPIs;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.HomeActivity;
import com.da.lon.wang.xlg.activity.LoginActivity;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.activity.ResultSearchActivity;
import com.da.lon.wang.xlg.activity.VideoActivity;
import com.da.lon.wang.xlg.activity.WebViewActivity;
import com.da.lon.wang.xlg.bean.AliPayBean;
import com.da.lon.wang.xlg.bean.CommentOrderInfo;
import com.da.lon.wang.xlg.bean.PayResult;
import com.da.lon.wang.xlg.bean.PictureOrderInfo;
import com.da.lon.wang.xlg.bean.ReplayInfo;
import com.da.lon.wang.xlg.bean.TopicInfo;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.imgupload.ChooseImageAvtivity;
import com.da.lon.wang.xlg.imgupload.ChooseListActivity;
import com.da.lon.wang.xlg.wxapi.WXPayBean;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.zxing.android.CaptureActivity;

import net.tsz.afinal.http.AjaxParams;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * webview工具类
 */

public class WebViewUtil {
    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private static final int SDK_PAY_FLAG = 1;
    public static Uri photoUri;
    public static boolean isHaveChoose = false;
    public static ReplayInfo replayInfo;
    public static TopicInfo topicInfo;
    public static CommentOrderInfo commentOrderInfo;
    public static PictureOrderInfo pictureOrderInfo;
    public static String customer_javascriptfunction;
    public static String wx_back_success_url;
    public static String wx_back_failed_url;
    public static String alipay_back_success_url;
    public static String alipay_back_failed_url;
    final IWXAPI msgApi;
    public ValueCallback<Uri> mUploadMsg;
    PayReq req;
    private Context context;
    private List<String> historyList;
    private String url = "";
    private WebView webView;
    private MyApplication aXlgApplication;
    private int background;
    private Message msg = null;
    // private ProgressBar progressbar;
    private OnLoading onLoading;
    private OnUrlLoad onUrlLoad;
    private boolean isregistedToWxApp = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                        loadUrl(rebuildUrl(WebViewUtil.alipay_back_success_url));
                    } else {
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(context, "支付结果确认中", Toast.LENGTH_SHORT)
                                    .show();

                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT)
                                    .show();
                            loadUrl(rebuildUrl(WebViewUtil.alipay_back_success_url));
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            Toast.makeText(context, "用户取消", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                        } else {
                            Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    public WebViewUtil(Context con) {
        context = con;
        historyList = new ArrayList<String>();
        msgApi = WXAPIFactory.createWXAPI(context, null);
        req = new PayReq();
        isregistedToWxApp = msgApi.registerApp(XLGConstants.WX_APP_ID);
    }

    public static boolean hasCamera(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    public static void takePhoto(Context context) {
        try {
            // 执行拍照前，应该先判断SD卡是否存在
            String SDState = Environment.getExternalStorageState();
            if (SDState.equals(Environment.MEDIA_MOUNTED) && hasCamera(context)) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
                photoUri = Uri.fromFile(getOutputMediaFile());
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        photoUri);
                ((Activity) context).startActivityForResult(intent, 2000);
            } else {
                Toast.makeText(context, "内存卡不存在", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile() {

        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory(),
                XLGConstants.FILE_PATH);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
        PreferenceUtils.getInstance().SetSettingString(
                "head_path",
                mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp
                        + ".jpg");
        return mediaFile;
    }

    public static String getPhotoPath() {
        if (photoUri != null) {
            return photoUri.toString().replace("file:///", "/");
        } else {
            return "";
        }
    }

    /**
     * 相册选择
     */

    public static void showImageChooseDialog1(final Context context) {

        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("").setMessage("").create();
        View view = LayoutInflater.from(context).inflate(
                R.layout.xlg_image_choose_dialog1, null);
        ((Button) view.findViewById(R.id.camera1))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {
                            if (MyApplication.getInstance().getImageInfosSize() >= HomeActivity.uploadMaxNum) {
                                Toast.makeText(
                                        context,
                                        "最多只能选" + HomeActivity.uploadMaxNum
                                                + "张", Toast.LENGTH_LONG)
                                        .show();
                            } else {
                                takePhoto(context);
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        ((Button) view.findViewById(R.id.ablum1))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        try {
                            Intent intent = new Intent(context,
                                    ChooseListActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("flg", "take");
                            intent.putExtras(bundle);
                            context.startActivity(intent);
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        // }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });

        ((Button) view.findViewById(R.id.video1))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {
                            Intent intent = new Intent(context,
                                    VideoActivity.class);
                            context.startActivity(intent);
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });

        ((Button) view.findViewById(R.id.cancle1))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        dialog.show();
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.xlg_image_choose_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (dm.widthPixels);
        dialog.getWindow().setAttributes(lp);
    }

    /**
     * 相册选择
     */

    public static void showImageChooseDialog(final Context context) {
        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("").setMessage("").create();
        View view = LayoutInflater.from(context).inflate(
                R.layout.xlg_image_choose_dialog, null);
        ((Button) view.findViewById(R.id.camera))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {
                            if (MyApplication.getInstance().getImageInfosSize() >= HomeActivity.uploadMaxNum) {
                                Toast.makeText(
                                        context,
                                        "最多只能选" + HomeActivity.uploadMaxNum
                                                + "张", Toast.LENGTH_LONG)
                                        .show();
                            } else {
                                takePhoto(context);
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        ((Button) view.findViewById(R.id.ablum))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {

                            Intent intent = new Intent(context,
                                    ChooseListActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("flg", "take");
                            intent.putExtras(bundle);
                            if (MyApplication.isMyoption()) {
                                ((Activity) context).startActivityForResult(
                                        intent, 2001);
                            } else {
                                context.startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
        ((Button) view.findViewById(R.id.cancle))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        dialog.show();
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.xlg_image_choose_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (dm.widthPixels);
        dialog.getWindow().setAttributes(lp);
    }

    public static void showsettingHeadLogDialog(final Context context) {

        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("").setMessage("").create();
        View view = LayoutInflater.from(context).inflate(
                R.layout.xlg_image_choose_dialog, null);
        ((Button) view.findViewById(R.id.camera))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {

                            if (MyApplication.getInstance().getImageInfosSize() >= HomeActivity.uploadMaxNum) {
                                Toast.makeText(
                                        context,
                                        "最多只能选" + HomeActivity.uploadMaxNum
                                                + "张", Toast.LENGTH_LONG)
                                        .show();
                            } else {
                                takePhoto(context);
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        ((Button) view.findViewById(R.id.ablum))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {
                            Intent intent = new Intent(context,
                                    ChooseListActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("flg", "setting");
                            intent.putExtras(bundle);
                            ((Activity) context).startActivityForResult(intent,
                                    1000);
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
        ((Button) view.findViewById(R.id.cancle))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        dialog.show();
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.xlg_image_choose_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (dm.widthPixels);
        dialog.getWindow().setAttributes(lp);
    }

    /**
     * 咨询人工客服
     */
    public static void startChat(Context context, String storecode,
                                 String storename, String useraccount, String usernickname,
                                 String goodsImageurl, String goodstitledetail, String goodsprice,
                                 String goodsurl) {

        boolean isEcChat = true;

        if (TextUtils.isEmpty(storecode)) {
            storecode = "pxokakfq";
        }
        if (TextUtils.isEmpty(storename)) {
            storename = "客服对话";
        }
        if (TextUtils.isEmpty(useraccount)) {
            useraccount = "游客";
        }
        if (TextUtils.isEmpty(usernickname)) {
            usernickname = "游客";
        }
        if (TextUtils.isEmpty(goodsImageurl)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodstitledetail)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsprice)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsurl)) {
            isEcChat = false;
        }

        KFAPIs.setTagNickname(usernickname + "(" + useraccount + ")", context);
        if (!isEcChat) {
            KFAPIs.startChat(context, storecode, // 1.
                    // 客服工作组ID(请务必保证大小写一致)，请在管理后台分配
                    storename, // 2. 会话界面标题，可自定义
                    null, // 3. 附加信息，在成功对接客服之后，会自动将此信息发送给客服;
                    // 如果不想发送此信息，可以将此信息设置为""或者null
                    false, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单,
                    // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示
                    // 显示:true, 不显示:false
                    5, // 5. 默认显示消息数量
                    null, // 6. 修改默认客服头像，如果不想修改默认头像，设置此参数为null
                    null, // 7. 修改默认用户头像, 如果不想修改默认头像，设置此参数为null
                    false, // 8. 默认机器人应答
                    isEcChat, null);
        } else {
            KFAPIs.startECChat(context, storecode, // 1.
                    // 客服工作组ID(请务必保证大小写一致)，请在管理后台分配
                    storename, // 2. 会话界面标题，可自定义
                    goodsurl, // 3.
                    // 附加信息，在成功对接客服之后，会自动将此信息发送给客服;
                    // 如果不想发送此信息，可以将此信息设置为""或者null
                    false, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单,
                    // 请务必至少分配三个且只分配三个自定义菜单,多于三个的暂时将不予显示
                    // 显示:true, 不显示:false
                    5, // 5. 默认显示消息数量
                    null, // 6. 修改默认客服头像，如果不想修改默认头像，设置此参数为null
                    null, // 7. 修改默认用户头像, 如果不想修改默认头像，设置此参数为null
                    false, // 8. 是否开启机器人应答

                    true, // 9.是否显示商品布局
                    goodsImageurl, // 10.商品图片网址
                    goodstitledetail, // 11.商品描述详情
                    goodsprice, // 12.商品价格

                    goodsurl, goodsurl, isEcChat, null);
        }

    }

    /**
     * 获取网页的html代码
     *
     * @param path
     * @return
     */
    public static String getWebHtml(String path) {
        String result = "";
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path)
                    .openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String temp = "";
            while ((temp = reader.readLine()) != null) {
                result += temp;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public void setOnloadingListener(OnLoading onLoading) {
        this.onLoading = onLoading;
    }

    public void setOnUrlLoadListener(OnUrlLoad onUrlLoad) {
        this.onUrlLoad = onUrlLoad;
    }

    /**
     * @param path                访问地址
     * @param javascriptInterface 与jsp交互 对象
     * @param webview             webview对象
     * @param background          设置默认webview显示背景 解决显示白屏
     */
    @SuppressLint("NewApi")
    public void setWebView(String path, JavaScriptExit javascriptInterface,
                           WebView webview, int background) {
        try {
            this.url = path;
            this.webView = webview;
            this.background = background;
            // 隐藏progressBar
            /*
             * progressbar = new ProgressBar(context, null,
             * android.R.attr.progressBarStyleHorizontal);
             * progressbar.setLayoutParams(new
             * LayoutParams(LayoutParams.MATCH_PARENT, 5, 0, 0));
             * webView.addView(progressbar);
             */
            //
            // // 支持缩放
            // web.getSettings().setSupportZoom(true);
            // web.getSettings().setBuiltInZoomControls(true);
            //
            // // 设置图片背景空
            // web.setBackgroundColor(0);
            // if (background != 0) {
            // web.setBackgroundDrawable(context.getResources().getDrawable(background));
            // }
            //
            // web.getSettings().setBlockNetworkImage(false);
            // web.getSettings().setRenderPriority(RenderPriority.HIGH);
            // // 应用数据
            // web.getSettings().setDomStorageEnabled(true);
            // web.getSettings().setAllowFileAccess(true);
            //
            webView.setVerticalScrollBarEnabled(false);
            webView.setVerticalScrollbarOverlay(false);
            webView.setHorizontalScrollBarEnabled(false);
            webView.setHorizontalScrollbarOverlay(false);
            webView.getSettings().setBuiltInZoomControls(false);

            // webView.clearHistory();
            // webView.clearFormData();
            // webView.clearCache(true);

            WebSettings webSettings = webView.getSettings();
            webSettings.setLoadWithOverviewMode(true); // 设置webview加载的页面的模式
            // setBuildInZoomControlsVisibility(webSettings, false);
            // webSettings.setBuiltInZoomControls(true);// 设置是否使用WebView内置的放大机制。
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 缓存模式(默认)

            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// javascript可自定打开窗口
            webSettings.setJavaScriptEnabled(true);// 启用javascript支持
            /**
             * 1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
             * 2、LayoutAlgorithm.SINGLE_COLUMN : 适应屏幕，内容将自动缩放
             */
            webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
            webSettings.setLightTouchEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setNeedInitialFocus(false);
            webSettings.setSupportMultipleWindows(true);
            webSettings.setDomStorageEnabled(true);
            webView.setWebChromeClient(new MyWebChromeClient());
            webView.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view,
                                                        final String path) {
                    historyList.add(path);
                    if (path.toUpperCase(Locale.CHINA).contains(
                            "okamiao".toUpperCase(Locale.CHINA))) {
                        Intent ewmIntent = new Intent(context,
                                CaptureActivity.class);
                        ((Activity) context).startActivityForResult(ewmIntent,
                                200);
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "all-product".toUpperCase(Locale.CHINA))) {

                        Intent intent = new Intent(context,
                                ResultSearchActivity.class);
                        String cid = null;
                        String sattr1 = null;

                        if (path.indexOf("sattr=") != -1) {
                            cid = path.substring(path.indexOf("cid=") + 4,
                                    path.indexOf("&"));
                            intent.putExtra("cid", cid);
                        } else {
                            cid = path.substring(path.indexOf("cid=") + 4);
                            intent.putExtra("cid", cid);
                        }

                        context.startActivity(intent);

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "type=active".toUpperCase(Locale.CHINA))) {

                        Intent intent = new Intent(context,
                                WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 002);
                        bundle.putString("url", path);
                        intent.putExtras(bundle);
                        context.startActivity(intent);

                        return true;

                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Index-index".toUpperCase(Locale.CHINA))) {
                        Intent intent = new Intent(context, HomeActivity.class);
                        context.startActivity(intent);

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "/p/".toUpperCase(Locale.CHINA))) {
                        Intent intent = new Intent(context,
                                ProductsActivity.class);
                        String product_number;
                        if (path.indexOf(".html") != -1) {
                            product_number = path.substring(
                                    path.indexOf("/p/") + 3,
                                    path.indexOf(".html"));
                        } else {
                            product_number = path.substring(
                                    path.indexOf("/p/") + 3, path.length());
                        }
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.PRODUCT_NUMBER,
                                product_number);
                        ((Activity) context).startActivityForResult(intent, 28);
                        return true;

                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Public-Login".toUpperCase(Locale.CHINA))) {
                        Intent loginIntent = new Intent(context,
                                LoginActivity.class);
                        loginIntent.putExtra("isGotoHome", true);
                        ((Activity) context).startActivityForResult(
                                loginIntent, 100);
                        ((Activity) context).finish();
                        return true;

                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Party-appinsert".toUpperCase(Locale.CHINA))) {

                        if (replayInfo != null) {
                            replayInfo = null;
                        }
                        try {
                            replayInfo = new ReplayInfo();
                            String content = path.substring(path.indexOf("?") + 1);
                            replayInfo.setComment_name(XLGDataUtils
                                    .getUrlParam(content, "comment_name"));
                            replayInfo.setTopic_id(XLGDataUtils.getUrlParam(
                                    content, "topic_id"));
                            replayInfo.setMember_id(XLGDataUtils.getUrlParam(
                                    content, "member_id"));
                            MyApplication.getInstance().deleteAllImageInfos();
                            HomeActivity.uploadType = ChooseImageAvtivity.TYPE_REPLAY;
                            HomeActivity.uploadMaxNum = 8;
                            showImageChooseDialog(context);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Party-addTopic".toUpperCase(Locale.CHINA))) {
                        if (topicInfo != null) {
                            topicInfo = null;
                        }
                        try {
                            topicInfo = new TopicInfo();
                            String content = path.substring(path
                                    .indexOf("party_id="));
                            topicInfo.setParty_id(content.substring(9));
                            MyApplication.getInstance().deleteAllImageInfos();
                            HomeActivity.uploadType = ChooseImageAvtivity.TYPE_TOPIC;
                            HomeActivity.uploadMaxNum = 8;
                            Intent intent = new Intent(context,
                                    ChooseImageAvtivity.class);
                            context.startActivity(intent);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Member-Logout".toUpperCase(Locale.CHINA))) {
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_KEY, "");
                        PreferenceUtils.getInstance().SetSettingString(
                                PreferencesConfig.USER_ID, "");
                        qqLogOut();

                        Intent intent = new Intent(context, HomeActivity.class);
                        ((Activity) context).startActivity(intent);

                        // return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Agent-fenxiang".toUpperCase(Locale.CHINA))) {

                        try {
                            String content = path.substring(path.indexOf("?") + 1);
                            String pro_name = XLGDataUtils.getUrlParam(content,
                                    "pro_name");
                            String uri = XLGDataUtils.getUrlParam(content,
                                    "uri");
                            if (pro_name == null) {
                                pro_name = "";
                            }
                            if (uri == null) {
                                uri = "";
                            }
                            Utils.showShare(context, URLDecoder.decode(pro_name, "utf-8"), null, URLDecoder.decode(uri, "utf-8"), null);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Music-addscenc".toUpperCase(Locale.CHINA))) {
                        Intent intent = new Intent(context,
                                ChooseImageAvtivity.class);
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_MUSIC;
                        HomeActivity.uploadMaxNum = 8;
                        context.startActivity(intent);
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Mages-Kf".toUpperCase(Locale.CHINA))) {
                        // KFAPIs.visitorLogin(context);
                        try {
                            String content = URLDecoder.decode(
                                    path.substring(path.indexOf("?") + 1),
                                    "utf-8");
                            String storecode = XLGDataUtils.getUrlParam(
                                    content, "storecode");
                            String storename = XLGDataUtils.getUrlParam(
                                    content, "storename");
                            String useraccount = XLGDataUtils.getUrlParam(
                                    content, "useraccount");
                            String usernickname = XLGDataUtils.getUrlParam(
                                    content, "usernickname");
                            String goodsImageurl = XLGDataUtils.getUrlParam(
                                    content, "goodsimageurl");
                            String goodstitledetail = XLGDataUtils.getUrlParam(
                                    content, "goodstitledetail");
                            String goodsprice = XLGDataUtils.getUrlParam(
                                    content, "goodsprice");
                            String goodsurl = XLGDataUtils.getUrlParam(content,
                                    "goodsurl");
                            startChat(context, storecode, storename,
                                    useraccount, usernickname, goodsImageurl,
                                    goodstitledetail, goodsprice, goodsurl);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "member-headupload".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_MODIFY_PHOTO;
                        HomeActivity.uploadMaxNum = 1;
                        showImageChooseDialog(context);
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Member-orderdelivery".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_ORDER_PICTURE;
                        HomeActivity.uploadMaxNum = 1;

                        if (pictureOrderInfo != null) {
                            pictureOrderInfo = null;
                        }
                        try {
                            pictureOrderInfo = new PictureOrderInfo();
                            String content = path.substring(path.indexOf("?") + 1);
                            pictureOrderInfo.setOrdersid(XLGDataUtils
                                    .getUrlParam(content, "ordersid"));
                            pictureOrderInfo.setLimitcount(XLGDataUtils
                                    .getUrlParam(content, "limitcount"));


                            showImageChooseDialog1(context);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "member-appevalu".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_COMMENT_ORDER;
                        HomeActivity.uploadMaxNum = 8;
                        if (commentOrderInfo != null) {
                            commentOrderInfo = null;
                        }
                        try {
                            commentOrderInfo = new CommentOrderInfo();
                            String content = path.substring(path.indexOf("?") + 1);
                            commentOrderInfo.setOid(XLGDataUtils.getUrlParam(
                                    content, "oid"));
                            commentOrderInfo.setPid(XLGDataUtils.getUrlParam(
                                    content, "pid"));
                            showImageChooseDialog(context);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "member-mytuikuan".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_SELL_MESSAGE;
                        HomeActivity.uploadMaxNum = 3;
                        showImageChooseDialog(context);
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "Member-Aftersales".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance()
                                .setTuikuan_message_url(path);

                        // return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "member-myfankui".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        HomeActivity.uploadType = ChooseImageAvtivity.TYPE_SUGGEST_MESSAGE;
                        HomeActivity.uploadMaxNum = 8;
                        MyApplication.setMyoption(true);
                        showImageChooseDialog(context);
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "member-index".toUpperCase(Locale.CHINA))) {

                        ((Activity) context).finish();
                        String decode;
                        try {
                            decode = URLDecoder.decode(path, "UTF-8");
                            if (decode.contains("message=")) {
                                if (MyApplication.getIs_skulist_enter_capture() == 1) {
                                    context.startActivity(new Intent(context,
                                            HomeActivity.class));
                                    MyApplication.getInstance()
                                            .getSkulist_activity().finish();
                                }
                                Utils.updateUserInfo(context);
                                int indexOf = decode.indexOf("message=");
                                String substring = decode.substring(
                                        indexOf + 8, decode.length());
                                ToastUtils.showShort(context, substring);
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "act=Ok_comupload".toUpperCase(Locale.CHINA))) {
                        MyApplication.getInstance().deleteAllImageInfos();
                        if (!TextUtils.isEmpty(customer_javascriptfunction)) {
                            customer_javascriptfunction = "";
                        }
                        try {

                            String content = path.substring(path.indexOf("?") + 1);
                            customer_javascriptfunction = XLGDataUtils
                                    .getUrlParam(content, "javascriptfunction");
                            HomeActivity.uploadType = ChooseImageAvtivity.TYPE_CUSTOMER_UPLOAD;
                            HomeActivity.uploadMaxNum = Integer
                                    .parseInt(XLGDataUtils.getUrlParam(content,
                                            "limitcount"));
                            showImageChooseDialog(context);
                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "needCoordinates=1".toUpperCase(Locale.CHINA))) {

                        onLoading.onGetLocation(path);

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "needNavigation=1".toUpperCase(Locale.CHINA))) {


                        boolean isBaiduInstall = XLGDataUtils.isInstallApp(
                                context, "com.baidu.BaiduMap");
                        boolean isGaodeInstall = XLGDataUtils.isInstallApp(
                                context, "com.autonavi.minimap");

                        aXlgApplication = (MyApplication) context
                                .getApplicationContext();
                        showMapChooseDialog(context, isBaiduInstall,
                                isGaodeInstall, aXlgApplication.latitude,
                                aXlgApplication.longitude, "目的地");

                        return true;
                    } else if (path.toUpperCase(Locale.CHINA).contains(
                            "cart-payment".toUpperCase(Locale.CHINA))) {

                        if (!TextUtils.isEmpty(wx_back_success_url)) {
                            wx_back_success_url = "";
                        }
                        if (!TextUtils.isEmpty(wx_back_failed_url)) {
                            wx_back_failed_url = "";
                        }
                        if (!TextUtils.isEmpty(alipay_back_success_url)) {
                            alipay_back_success_url = "";
                        }
                        if (!TextUtils.isEmpty(alipay_back_failed_url)) {
                            alipay_back_failed_url = "";
                        }
                        try {
                            String content = URLDecoder.decode(
                                    path.substring(path.indexOf("?") + 1),
                                    "utf-8");
                            String msn = XLGDataUtils.getUrlParam(content,
                                    "msn");
                            String paycode = XLGDataUtils.getUrlParam(content,
                                    "paycode");
                            if (!TextUtils.isEmpty(msn)
                                    && !TextUtils.isEmpty(paycode)) {
                                if (paycode.equals("weixin")) {
                                    gotoWeixinPay(msn);
                                    return true;
                                } else if (paycode.equals("alipaywap")) {
                                    gotoAliPay(msn);
                                    return true;
                                }
                            }

                        } catch (Exception e) {
                            Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                    url = path;
                    return super.shouldOverrideUrlLoading(view,
                            rebuildUrl(path));
                }

                // Beginning page load
                @Override
                public void onPageStarted(WebView view, String path,
                                          Bitmap favicon) {
                    super.onPageStarted(view, path, favicon);
                    if (!path.toUpperCase(Locale.CHINA).contains(
                            "Public-Login".toUpperCase(Locale.CHINA))) {
                        url = path;
                    }
                    onLoading.onStart(path);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode,
                                            String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description,
                            failingUrl);

                    view.stopLoading();
                    onLoading.onError();
                }

                @Override
                public void onReceivedSslError(WebView view,
                                               SslErrorHandler handler, SslError error) {
                    handler.proceed();
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    view.getSettings().setBlockNetworkImage(false);
                    Calendar cal = Calendar.getInstance();
                    cal.set(Calendar.HOUR, Calendar.HOUR - 1);
                    long time = cal.getTimeInMillis();
                    clearCacheFolder(context.getCacheDir(), time);
                    view.loadUrl("javascript:$(\".new-header\").hide();$(\".o-cter\").css('margin-top','0')");
                    onLoading.onComplete(url);
                }

            });

            webView.loadUrl(url);
            if (url.contains("Store-assuid-store_id-") && !url.contains("user_key")) {
                String sr = "Store-assuid-store_id-";
                int indexOf = url.indexOf(sr);
                int index = url.indexOf("?");
                String substring = url.substring(indexOf + sr.length(), index);
                if (!"".equals(substring)) {
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.STORE_ID, substring);
                }
            }
            if (javascriptInterface != null) {
                webview.addJavascriptInterface(javascriptInterface, "ExitApp");
            }
            historyList.add(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadUrl(String url) {
        try {
            if (url.contains("needCoordinates=1")) {
                onLoading.onGetLocation(url);
            } else {
                webView.loadUrl(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadUrl() {
        webView.loadUrl(rebuildUrl(url));
    }

    public String rebuildUrl(String url) {
        String id = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_ID, "");
        String user_key = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_KEY, "");
        String encode_user_key;
        try {
            encode_user_key = URLEncoder.encode(user_key, "utf-8");
        } catch (UnsupportedEncodingException e) {
            encode_user_key = user_key;
        }
        String mUrl = url;
        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(user_key)) {
            if (mUrl.contains("?")) {
                mUrl = mUrl + "id=" + id + "&user_key=" + encode_user_key
                        + "&qt=1" + "&version=21";
            } else {
                mUrl = mUrl + "?id=" + id + "&user_key=" + encode_user_key
                        + "&qt=1" + "&version=21";
            }

        } else {
            if (!mUrl.contains("?")) {
                mUrl = mUrl + "?qt=1" + "&version=21";
            } else {
                mUrl = mUrl + "&qt=1" + "&version=21";
            }

        }

        return mUrl;
    }

    public void webViewReload() {
        try {
            webView.reload();
            webView.setBackgroundColor(0);
            if (background != 0) {
                webView.setBackgroundDrawable(context.getResources()
                        .getDrawable(background));
            }
            int stat = getRequestContent(url);
            if (stat == 200 || stat == 303 || stat == 301 || stat == 302
                    || stat == 307) {
                webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                webView.reload();
            } else {
                webView.stopLoading();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> getHistoryList() {
        return historyList;
    }

    public int getHistoryLength() {
        return historyList.size();
    }

    public int getRequestContent(String url) {
        int status = 0;
        // 是否没网络
        if (!isNetWork() && !isWifi()) {
            return status = 404;
        }
        HttpParams params = new BasicHttpParams();
        // 连接时间读取时间，设置为3秒
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        HttpHead head = new HttpHead(url);
        HttpResponse response;

        try {
            response = httpClient.execute(head);
            // 页面正常连接返回成功为200
            status = response.getStatusLine().getStatusCode();
        } catch (ConnectTimeoutException e) {
            // 连接超时
            status = -1;
        } catch (Exception e) {
            status = 404;
        } finally {
            try {
                head.clone();
            } catch (CloneNotSupportedException e) {

            }
        }
        return status;
    }

    private int clearCacheFolder(File dir, long numDays) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }

                    if (child.lastModified() < numDays) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    public boolean isNetWork() {
        boolean status = false;
        try {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                // 网线
                NetworkInfo mNetworkInfo = mConnectivityManager
                        .getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    status = mNetworkInfo.isAvailable();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return status;
    }

    public boolean isWifi() {
        boolean status = false;
        try {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                // 网线
                NetworkInfo mNetworkInfo = mConnectivityManager
                        .getActiveNetworkInfo();
                // wifi
                NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (mWiFiNetworkInfo != null) {
                    status = mWiFiNetworkInfo.isAvailable();
                } else if (mNetworkInfo != null) {
                    status = mNetworkInfo.isAvailable();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 退出qq登陆
     */
    private void qqLogOut() {
        Tencent tencent = Tencent.createInstance(XLGConstants.APP_ID, context);
        if (tencent != null) {
            tencent.logout(context);
            tencent.releaseResource();
        }
    }

    /**
     * 请求微信支付参数
     */

    private void gotoWeixinPay(String orderId) {
        if (!MyApplication.getInstance().isWXAppInstalledAndSupported()) {
            ToastUtils.showShort(context, "你尚未安裝微信,请先安装微信！");
            return;
        }
        final ProgressDialog dialog = ProgressDialog.show(context, "提示", "加载中");

        String url = XLGConstants.URL + "Order-weixin";

        HttpLoader<WXPayBean> httpLoader = new HttpLoader<WXPayBean>(context,
                url, WXPayBean.class);
        AjaxParams params = new AjaxParams();
        try {
            params.put(
                    "id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put(
                    "user_key",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_KEY, ""));
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Order" + XLGConstants.SECRET
                            + "weixin"));
            params.put("device_type", "1");
            params.put("type", "1");
            params.put("msn", orderId);
            httpLoader.setManagerListener(new OnWebLoadListener<WXPayBean>() {

                @Override
                public void OnStart() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void OnError(String error) {
                    Toast.makeText(context, "下单失败", Toast.LENGTH_SHORT).show();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }

                @Override
                public void onSuccess(WXPayBean t) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (t != null && t.code.equals("000000")) {

                        WXPayBean.WXPayResult result = t.result;
                        req.appId = result.appid;
                        req.partnerId = result.partnerid;
                        req.prepayId = result.prepayid;
                        req.packageValue = "Sign=WXPay";
                        req.nonceStr = result.noncestr;
                        req.timeStamp = result.timestamp;
                        req.sign = result.sign;
                        wx_back_success_url = result.return_url;
                        wx_back_failed_url = result.cancel_url;

                        if (!isregistedToWxApp) {
                            isregistedToWxApp = msgApi.registerApp(result.appid);
                        }

                        msgApi.sendReq(req);

                    } else {
                        Toast.makeText(context, "下单失败", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 请求支付宝支付参数
     */

    private void gotoAliPay(String orderId) {
        final ProgressDialog dialog = ProgressDialog.show(context, "提示", "加载中");
        String url = XLGConstants.URL + "Order-weixin";

        HttpLoader<AliPayBean> httpLoader = new HttpLoader<AliPayBean>(context,
                url, AliPayBean.class);
        AjaxParams params = new AjaxParams();
        try {
            params.put(
                    "id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put(
                    "user_key",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_KEY, ""));
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Order" + XLGConstants.SECRET
                            + "weixin"));
            params.put("device_type", "1");
            params.put("type", "2");
            params.put("msn", orderId);
            httpLoader.setManagerListener(new OnWebLoadListener<AliPayBean>() {

                @Override
                public void OnStart() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void OnError(String error) {
                    Toast.makeText(context, "下单失败", Toast.LENGTH_SHORT).show();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }

                @Override
                public void onSuccess(AliPayBean t) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (t != null && t.getCode().equals("000000")) {
                        AliPayBean.AliPayResult result = t.getResult();
                        String alipaystr = result.alipaystr;
                        alipay_back_success_url = result.return_url;
                        alipay_back_failed_url = result.cancel_url;

                        alipay(alipaystr);

//                        String s = "alipay_sdk=alipay-sdk-php-20161101&app_id=2016080300159375&biz_content=%7B%22body%22%3A%22%E5%AE%9E%E7%89%A9%E8%AE%A2%E5%8D%95_280546129176709010%22%2C%22subject%22%3A+%22%E5%AE%9E%E7%89%A9%E8%AE%A2%E5%8D%95_280546129176709010%22%2C%22out_trade_no%22%3A+%22280546129176709010%22%2C%22passback_params%22%3A+%22order_type%253Dreal_order%22%2C%22timeout_express%22%3A+%2230m%22%2C%22total_amount%22%3A+%22718.00%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fcs.j.cqxueao.cn%2Fmobileapp%2Fapi%2Fpayment%2Falipayapp%2Fnotify_url.php&sign_type=RSA2&timestamp=2017-04-21+22%3A33%3A43&version=1.0&sign=XfoziniAicX9MgE3JBpJyH2FezgiukgOcM0UdQT%2BPYhrDKKSqVTRnkitc72grf4OfRfiIMggX78z3D0299ifGY4Ew8bUNTZjgK0%2BdJ%2FXqfMKXpwXvTMWj%2FhZAU7p4l29Hp3RSleNUv57QJRVGKbtolWnTnxj9n41t58yUiSTBYHiPfeIBBDK0TxxjZhSlS5qCEoLDKkWM0%2FIVpHMTZ3%2BSPFkzog0BX1hQ%2BCQXkWzFs7fgVqHhwBMbTSknA9vBCij2vKa5Ql1Ip8HJiQhk9Pq%2F6lFxIWmhbGqnINm60413Wj9FvWmuQeRDe9zz4q6zpaMTOdUFoXopBbMOD8UCzrOVQ%3D%3D";
//                        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//                        alipay(s);
                    } else {
                        Toast.makeText(context, "下单失败", Toast.LENGTH_SHORT)
                                .show();
                    }

                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {


        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) context);
                String result = alipay.pay(payInfo, true);
                //String result = alipay.payV2(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 是否安装支付宝
     */

    private boolean isInstallAlipay() {
        boolean isInstall = false;

        try {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
            // 从pinfo中将包名字逐一取出，压入pName list中
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    pName.add(pn);
                }
            }
            isInstall = pName.contains("com.alipay.android.app");// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
        } catch (Exception e) {

        }

        return isInstall;
    }

    /**
     * 地图选择
     */

    public void showMapChooseDialog(final Context context,
                                    boolean isBaiduInstall, boolean isGaodeInstall,
                                    final double des_lat, final double des_lon, final String des_name) {
        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setTitle("").setMessage("").create();
        View view = LayoutInflater.from(context).inflate(
                R.layout.xlg_map_choose_dialog, null);
        Button baidu = (Button) view.findViewById(R.id.baidu);
        Button gaode = (Button) view.findViewById(R.id.gaode);
        if (!isBaiduInstall) {
            baidu.setVisibility(View.GONE);
        }
        if (!isGaodeInstall) {
            gaode.setVisibility(View.GONE);
        }

        baidu.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // 调起百度地图客户端
                try {
                    double[] des = bd_encrypt(des_lat, des_lon);
                    // 移动APP调起Android百度地图方式举例
                    Intent intent = Intent
                            .getIntent("intent://map/marker?location="
                                    + des[0]
                                    + ","
                                    + des[1]
                                    + "&title=我的位置&content=百度奎科大厦&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                    context.startActivity(intent); // 启动调用
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        });
        gaode.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {

                    Intent intent = new Intent(
                            "android.intent.action.VIEW",
                            android.net.Uri
                                    .parse("androidamap://navi?sourceApplication=appname&poiname="
                                            + des_name
                                            + "&lat="
                                            + des_lat
                                            + "&lon="
                                            + des_lon
                                            + "&dev=0&style=2"));
                    intent.setPackage("com.autonavi.minimap");
                    context.startActivity(intent);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        });
        ((Button) view.findViewById(R.id.cancle))
                .setOnClickListener(new android.view.View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }
                });
        dialog.show();
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.xlg_image_choose_dialog_style);
        dialog.setCanceledOnTouchOutside(true);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (dm.widthPixels);
        dialog.getWindow().setAttributes(lp);
    }

    private double[] bd_encrypt(double gg_lat, double gg_lon) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double[] des = new double[2];
        double x = gg_lon;
        double y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        des[1] = z * Math.cos(theta) + 0.0065;
        des[0] = z * Math.sin(theta) + 0.006;
        return des;

    }

    public interface OnGetTitle {
        public void getTitle(String title);
    }

    public interface OnLoading {
        public void onStart(String url);

        public void onComplete(String url);

        public void onError();

        public void onGetLocation(String url);
    }

    public interface OnUrlLoad {
        public void onLoad(String url);
    }

    final class MyWebChromeClient extends WebChromeClient {
        private Uri imageUri;

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean dialog,
                                      boolean userGesture, Message resultMsg) {
            return super.onCreateWindow(view, dialog, userGesture, resultMsg);
        }

        /**
         * 覆盖默认的window.alert展示界面，避免title里显示为“：来自file:////”
         */
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());

            builder.setTitle("对话框").setMessage(message)
                    .setPositiveButton("确定", null);

            builder.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    return true;
                }
            });

            builder.setCancelable(false);

            result.confirm();
            return true;
        }

        public boolean onJsBeforeUnload(WebView view, String url,
                                        String message, JsResult result) {
            return super.onJsBeforeUnload(view, url, message, result);
        }

        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());
            builder.setTitle("对话框").setMessage(message)
                    .setPositiveButton("确定", new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    }).setNeutralButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            builder.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.cancel();
                }
            });

            // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
            builder.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    return true;
                }
            });
            // 禁止响应按back键的事件
            // builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
            // return super.onJsConfirm(view, url, message, result);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            mUploadMsg = uploadMsg;
            File imageStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "MyApp");
            // Create the storage directory if it does not exist
            if (!imageStorageDir.exists()) {
                imageStorageDir.mkdirs();
            }
            File file = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            imageUri = Uri.fromFile(file);

            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = context.getPackageManager();
            final List<ResolveInfo> listCam = packageManager
                    .queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent i = new Intent(captureIntent);
                i.setComponent(new ComponentName(res.activityInfo.packageName,
                        res.activityInfo.name));
                i.setPackage(packageName);
                i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                cameraIntents.add(i);
            }

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                    cameraIntents.toArray(new Parcelable[]{}));
            ((Activity) context).startActivityForResult(chooserIntent, 1000);

        }

        /**
         * 覆盖默认的window.prompt展示界面，避免title里显示为“：来自file:////”
         * window.prompt('请输入您的域名地址', '618119.com');
         */
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, final JsPromptResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());

            builder.setTitle("对话框").setMessage(message);

            final EditText et = new EditText(view.getContext());
            et.setSingleLine();
            et.setText(defaultValue);
            builder.setView(et).setPositiveButton("确定", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm(et.getText().toString());
                }

            }).setNeutralButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });

            builder.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    return true;
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();
            return true;

        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }


}
